package com.wolfden.drugserver.warping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.bukkit.Location;
import org.bukkit.plugin.Plugin;

import com.wolfden.drugserver.utils.FileUtils;

public class WarpMap {

	private HashMap<String, SerializableLocation> warpMap;
	private Plugin plugin;

	public WarpMap(Plugin plugin) {
		this.plugin = plugin;
		load();
	}

	public void save() {

		try {
			FileUtils.save("warps.bin", this.warpMap);
		} catch (IOException e1) {
			plugin.getLogger().info("Trouble saving warps.bin");
			e1.printStackTrace();
		}

		plugin.getLogger().info("WarpMap Saved");
	}

	@SuppressWarnings("unchecked")
	public void load() {

		try {
			this.warpMap = (HashMap<String, SerializableLocation>) FileUtils.load("warps.bin");
		} catch (IOException e1) {
			this.warpMap = new HashMap<String, SerializableLocation>();
			plugin.getLogger().info("warps.bin not loaded, created new WarpMap.");
		}
	}

	public ArrayList<String> getWarpsList() {

		return new ArrayList<String>(this.warpMap.keySet());
	}

	public Location getWarpLocation(String warpName) {

		return this.warpMap.get(warpName).getLocation(plugin.getServer());
	}

	public void addWarp(String warpName, SerializableLocation warpLocation) {

		this.warpMap.put(warpName, warpLocation);
		save();
	}

	public boolean removeWarp(String warpName) {

		if (warpMap.keySet().contains(warpName)) {
			this.warpMap.remove(warpName);
			save();
			return true;
		} else {
			return false;
		}

	}

	public boolean renameWarp(String oldWarpName, String newWarpName) {

		if (this.warpMap.get(newWarpName) != null) {
			return false;
		} else {
			SerializableLocation location = this.warpMap.get(oldWarpName);
			this.warpMap.remove(oldWarpName);
			this.warpMap.put(newWarpName, location);
			save();
			return true;
		}
	}
}
